from qiniu import Auth, put_file, etag
import qiniu.config
from django.http import JsonResponse

import time

class Qiniu_Tool:
    def __init__(self):
        # 初始化七牛云的access_key、secret_key、bucket_name和domain
        self.access_key = 'hQetOcWidEv4RqXaGD0p0917C3LEUkBcd1Cc9umP'
        self.secret_key = 'h_7Ch03aD1JBIHX-_HtzIGYnwQZNgh7_YIdLSRbs'
        self.bucket_name = 'china-xiaobai'
        self.domain="syhx7nmey.hb-bkt.clouddn.com"
        # 生成七牛云的认证对象
        self.q = Auth(self.access_key, self.secret_key)

    def qiniu_token(self, key=None):
        """生成上传 Token"""
        # 生成上传 Token
        token = self.q.upload_token(self.bucket_name, key, 3600)
        print(token)
        return {"code": 10000, "data": token}  # 直接返回字典

    def qiniu_upload(self, file_path, key):
        """
        上传文件到七牛云
        :param file_path: 本地文件路径
        :param key: 上传到七牛云的文件名
        :return: 上传结果
        """
        # 生成上传 Token
        token = self.q.upload_token(self.bucket_name, key, 3600)

        try:
            # 调用put_file上传文件
            ret, info = put_file(token, key, file_path, version='v2')

            # 打印调试信息
            print("Upload result:", ret)
            print("Upload info:", info)

            if ret and ret.get('key') == key:
                # 验证文件哈希值
                assert ret['hash'] == etag(file_path)
                return {
                    "code": 10000,
                    "data": {
                        "key": ret['key'],
                        "hash": ret['hash'],
                        "url": f"http://{self.bucket_name}.qiniudn.com/{key}"  # 可根据需要修改域名
                    }
                }
            else:
                return {
                    "code": 10001,
                    "message": "Upload failed",
                    "details": info
                }
        except Exception as e:
            return {
                "code": 10002,
                "message": "Upload error",
                "error": str(e)
            }

    def get_file_url(self, key, with_timestamp=False):
        """
        获取文件访问URL（精简版）
        :param key: 文件key
        :param with_timestamp: 是否添加时间戳防止缓存
        :return: 文件URL字符串
        """
        # 获取文件访问URL
        base_url = f'http://{self.domain}/{key}'
        if with_timestamp:
            return f"{base_url}?t={int(time.time())}"
        return base_url





